package com.xy.biz.xd.service.impl;

import com.xy.biz.fd.client.DocumentClient;
import com.xy.biz.fd.domain.req.document.SaveDocumentRequest;
import com.xy.biz.mc.client.MessagePushClient;
import com.xy.biz.mc.domain.Message;
import com.xy.biz.mc.domain.consts.MessageTypeConstant;
import com.xy.biz.mc.domain.req.MessagePushRequest;
import com.xy.biz.xd.domain.bo.*;
import com.xy.biz.xd.domain.converter.DocumentFlowBorrowAndPrintAndDropConverter;
import com.xy.biz.fd.domain.enums.DocumentDefaultRepositoryEnum;
import com.xy.biz.xd.domain.query.DocumentReleaseQuery;
import com.xy.biz.xd.domain.req.ApplyDocumentFlowDropRequest;
import com.xy.biz.xd.domain.req.ReleaseDocumentFlowNewRequest;
import com.xy.biz.xd.domain.req.UploadDocumentFlowModifyRequest;
import com.xy.biz.xd.manager.*;
import com.xy.biz.xd.service.DocumentFlowDropService;
import com.xy.lang.domain.Result;
import com.xy.lang.domain.tuples.Triple;
import com.xy.lang.util.ResultUtils;
import com.xy.tool.context.UserContextHolder;
import com.xy.tool.gid.service.GidService;
import com.xy.tool.json.JsonUtils;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.xy.biz.xd.domain.bo.DocumentFlowConstants.*;
import static com.xy.biz.xd.domain.bo.DocumentReleaseBO.*;

@Service
public class DocumentFlowDropServiceImpl extends AbstractDocumentFlowBorrowAndPrintAndDropServiceImpl implements DocumentFlowDropService {

    @Autowired
    private DocumentClient documentClient;
    @Autowired
    private DocumentFlowManager documentFlowManager;
    @Autowired
    private DocumentFlowServiceSupport documentFlowServiceSupport;
    @Autowired
    DocumentFlowBorrowAndPrintAndDropManager documentFlowBorrowAndPrintAndDropManager;
    private String type = "作废";

    @Override
    protected String getType() {
        return type;
    }

    @Transactional
    @Override
    public Result<?> saveDocumentFlow(ApplyDocumentFlowDropRequest request) {
        List<DocumentFlowBorrowAndPrintAndDropBO> documentFlowBorrowAndPrintAndDropBOList = DocumentFlowBorrowAndPrintAndDropConverter.toBOList(request);
        DocumentFlowBorrowAndPrintAndDropBO documentFlowDropBO = buildDocumentFlowBorrowAndPrintAndDropList(documentFlowBorrowAndPrintAndDropBOList, FLOW_TYPE_DROP);
        Task task = documentFlowServiceSupport.startFirstTask(documentFlowDropBO, PROCESS_COMMON_FLOW, request.getNextHandleUserId());
        String foreignKey = task.getProcessInstanceId();
        documentFlowDropBO.setForeignKey(foreignKey);
        int row = documentFlowBorrowAndPrintAndDropManager.saveAllDocumentFlowBorrowAndPrintAndDrop(documentFlowBorrowAndPrintAndDropBOList);
        if (row > 0) {
            //定义消息内容
            Message message = Message.builder()
                    .type(MessageTypeConstant.TYPE_FLOW)
                    .data(1)
                    .path(MessageTypeConstant.FLOW_LIST)
                    .remark("作废流程-文件审核")
                    .build();
            sendMessage(message, request.getNextHandleUserId());
        }
        return Result.success();
    }

    @Transactional
    @Override
    public Result<?> releaseDocumentFlow(ReleaseDocumentFlowNewRequest request) {
        DocumentFlowBO documentFlowBO = documentFlowManager.getDocumentFlow(request.getDocumentFlowId());
        if (Objects.isNull(documentFlowBO)) {
            return Result.ofNotFound(String.valueOf(request.getDocumentId()));
        }
        Integer batchType = documentFlowBO.getBatchType();
        Result<Triple<List<DocumentFlowBO>, List<Long>, List<Long>>> result;
        if (!(result = saveDocumentReleaseList(request, documentFlowBO, batchType)).wasSuccess()) {
            return result;
        }
        Triple<List<DocumentFlowBO>, List<Long>, List<Long>> triple = ResultUtils.get(result);
        Set<Long> documentIdSet = triple.getValue1().stream().map(DocumentFlowBO::getDocumentId).collect(Collectors.toSet());
        //解锁原文档
        documentClient.updateDocumentByIds(SaveDocumentRequest.builder().documentFlowLock(false).documentIds(new ArrayList<>(documentIdSet)).build());
//        //删掉各个现行知识库的相关文件
//        //删除掉所有签收记录
//        List<DocumentReleaseBO> documentReleaseBOList = documentReleaseManager.listDocumentRelease(DocumentReleaseQuery.max()
//                .documentIdS(Collections.singletonList(request.getDocumentId())).build());
//        if (CollectionUtils.isEmpty(documentReleaseBOList)) {
//            return Result.ofBadRequest("未查询到签收记录");
//        }
//        Set<Long> collect = documentReleaseBOList.stream().map(DocumentReleaseBO::getDocumentReleaseId).collect(Collectors.toSet());
//        documentReleaseCheckManager.deleteDocumentReleaseCheckByDocumentReleaseId(collect);
        //定义消息内容
        Message message = Message.builder()
                .type(MessageTypeConstant.TYPE_FLOW)
                .data(1)
                .path(MessageTypeConstant.DOCUMENT_RELEASE_CHECK)
                .remark("编号《" + documentFlowBO.getDocumentCode() + "》文件已被作废")
                .build();
        Set<Long> userIdSet = buildMessageReceiveUserIdCollection(triple.getValue2(), triple.getValue3());
        for (Long userId : userIdSet) {
            sendMessage(message, userId);
        }
        return Result.success();
    }
}
